package com.oracle.lingshangejia.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.oracle.lingshangejia.Constant;
import com.oracle.lingshangejia.R;
import com.oracle.lingshangejia.activity.AboutUsActivity;
import com.oracle.lingshangejia.activity.FeedBackActivity;
import com.oracle.lingshangejia.activity.SettingsActivity;
import com.oracle.lingshangejia.base.BaseFragment;
import com.oracle.lingshangejia.bean.DataBean;
import com.oracle.lingshangejia.bean.ImgBean;
import com.oracle.lingshangejia.bean.UserBean;
import com.oracle.lingshangejia.utils.FileUtil;
import com.oracle.lingshangejia.utils.MyLogger;
import com.oracle.lingshangejia.utils.MyToast;
import com.oracle.lingshangejia.utils.ObserverOnNext;
import com.oracle.lingshangejia.utils.OkHttpUtils;
import com.oracle.lingshangejia.utils.RxUtils;
import com.oracle.lingshangejia.utils.SpUtils;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

import static android.app.Activity.RESULT_OK;
//我的

public class MyFragment extends BaseFragment implements View.OnClickListener {

    private LinearLayout ll_information;
    private LinearLayout ll_message;
    private LinearLayout ll_feedback;
    private LinearLayout ll_about_us;
    private LinearLayout ll_settings;
    private TextView mTvName;
    private TextView mTvCommunity;
    private ImageView mIvHead;
    private UserBean mUserBean;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void onBindViewBefore(View view) {

        ll_information=view.findViewById(R.id.ll_information);
       // ll_message=view.findViewById(R.id.ll_message);
        ll_feedback=view.findViewById(R.id.ll_feedback);
        ll_about_us=view.findViewById(R.id.ll_about_us);
        ll_settings=view.findViewById(R.id.ll_settings);
        ll_information.setOnClickListener(this);
      //  ll_message.setOnClickListener(this);
        ll_feedback.setOnClickListener(this);
        ll_about_us.setOnClickListener(this);
        ll_settings.setOnClickListener(this);
        mIvHead = view.findViewById(R.id.iv_head);
        mTvCommunity = view.findViewById(R.id.tv_community);
        mTvName = view.findViewById(R.id.tv_name);
        mIvHead.setOnClickListener(this);
        showLoading();

    }

    @Override
    protected void initData() {

        getData();
    }

    @Override
    public void onResume() {
        super.onResume();


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){

            //个人信息
            case R.id.iv_head:
                openPhoto();

              //  startActivity(new Intent(getActivity(),InformationActivity.class));
                break;

            //我的消息
            /*case R.id.ll_message:
                startActivity(new Intent(getActivity(),MessageActivity.class));
                break;*/

            //意见反馈
            case R.id.ll_feedback:
                startActivity(new Intent(getActivity(),FeedBackActivity.class));
                break;

            //关于我们
            case R.id.ll_about_us:
                startActivity(new Intent(getActivity(), AboutUsActivity.class));
                break;

            //设置
            case R.id.ll_settings:
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST && resultCode == RESULT_OK) {
            LocalMedia localMedia = PictureSelector.obtainMultipleResult(data).get(0);
            RequestOptions requestOptions = new RequestOptions().placeholder(R.drawable.ic_info_user)
                    .circleCropTransform();
            Glide.with(mIvHead.getContext()).load(localMedia.getCompressPath())
                    .apply( requestOptions)
                    .into(mIvHead);
            Observable.create(new ObservableOnSubscribe<Integer>() {
                @Override
                public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {

                    List<File> files = new ArrayList<>();
                    File file = new File(localMedia.getCompressPath());
                    files.add(file);
                    okhttp3.Response response  = OkGo.<String>post(Constant.baseurl+"open/uploadImg")
                            .tag(this)//
                            .isMultipart(true)
                            .addFileParams("files", files).execute();
                    Gson gson = new Gson();
                    ImgBean bean = gson.fromJson(response.body().string(), ImgBean.class);
                    if (bean.getCode() == 0) {
                        //图片上成功 获取图片id
                        int mImage = Integer.valueOf(bean.getFileUrl().get(0));
                        String token = (String) SpUtils.get(getContext(),"token", "");
                        int mark= (int) SpUtils.get(getContext(),"mark",0);
                        Map<Object,Object> params = new HashMap<>();
                        params.put("picId", mImage);
                        params.put("token",token);
                        params.put("mark",mark);
                        params.put("userId", mUserBean.getData().getId());
                        JSONObject jsonObject = new JSONObject(params);
                        okhttp3.Response re  = OkGo.<String>post(Constant.baseurl+"online/user/updateImg")
                                .upJson(jsonObject.toString())
                                .execute();
                        DataBean dataBean = gson.fromJson(re.body().string(),DataBean.class );

                        if (dataBean.getCode() == 0){
                            emitter.onNext(0);
                        }else {
                            emitter.onError(null);
                        }

                    }



                }
            }).compose(RxUtils.io_main()).subscribe(new ObserverOnNext<Integer>() {
                @Override
                public void onNext(Integer s) {
                       if (s == 0){
                           MyToast.show("头像更换成功");
                       }
                }
            });


       }
    }

    //打开相册
    private void openPhoto(){
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()/主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                .maxSelectNum(1)// 最大图片选择数量 int
                .minSelectNum(1)// 最小选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .previewImage(true)// 是否可预览图片 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                // .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                .withAspectRatio(1,1)
                .enableCrop(true)// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
                .compressSavePath(FileUtil.getPath())//压缩图片保存地址
                .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                .previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .isDragFrame(false)// 是否可拖动裁剪框(固定)
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            dismissLoading();
            switch (msg.what){

                case 1:

                    Gson gson = new Gson();
                    mUserBean = gson.fromJson((String) msg.obj,UserBean.class );
                    if ( mUserBean.getCode() == 0){

                        mTvName.setText(mUserBean.getData().getName());
                            if (!TextUtils.isEmpty(mUserBean.getData().getYymc())){
                                mTvCommunity.setText(mUserBean.getData().getYymc());

                            }
                             //设置头像
                            if (!TextUtils.isEmpty(mUserBean.getData().getPicUrl())){
                                Glide.with(mIvHead.getContext()).load(Constant.imgurl+ mUserBean.getData().getPicUrl())
                                        .apply(new RequestOptions().circleCrop().error(R.mipmap.ic_user))
                                        .into(mIvHead);
                                         MyLogger.i(mUserBean.getData().getPicUrl());
                            }
                        SpUtils.put(getContext(),"name" , mUserBean.getData().getName());

                        }
                    break;
                case 2: //连接上服务器，错误
                    String error= (String) msg.obj;
                    Toast.makeText(getActivity(),error,Toast.LENGTH_SHORT).show();
                    break;
                case 3:  //没有网络
                    Toast.makeText(getActivity(),"网络不可用",Toast.LENGTH_SHORT).show();
                    break;
                case 4: //没有连接上服务器
                    Toast.makeText(getActivity(),"连接服务器失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    public void getData(){

        HashMap<Object,Object> map = new HashMap<>();
        map.put("token", SpUtils.get(getActivity(),"token",""));
        map.put("mark", SpUtils.get(getActivity(),"mark",1));
        map.put("userId", SpUtils.get(getActivity(),"ysid",0));
        OkHttpUtils.getNetWork(getActivity(), Constant.baseurl+"online/user/getUserDetail",map,handler);
    }
}
